package main

import (
	"TDD/src/transaction"
	"TDD/src/user"
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"sync"
)

func main() {
    const bufLen = 100 
    transactions := make(chan transaction.Transaction, bufLen)
    trsResults := make(chan transaction.TransactionResult, bufLen)

    var wg sync.WaitGroup

    wg.Add(1)
    go transaction.ProcessTransactions(transactions, trsResults, &wg)
    

    users := []user.User {
        {ID: 1, Balance: 300, Mutex: &sync.Mutex{}},
        {ID: 2, Balance: 1000, Mutex: &sync.Mutex{}},
        {ID: 3, Balance: 500.22, Mutex: &sync.Mutex{}},
    }

    fmt.Printf("\nВадим: ID = %d, Balance = %f. \nЭлис: ID = %d, Balance = %f. \nАлекс: ID = %d, Balance = %f. \nВведите транзакции в формате 'fromID toID amount' ('exit' для выхода)", users[0].ID, users[0].Balance, users[1].ID, users[1].Balance, users[2].ID, users[2].Balance)

    trsCounter := 0 
    var mu sync.Mutex

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        input := scanner.Text()
        if input == "exit" {
            break
        }

        inpParts := strings.Split(input, " ")
        if len(inpParts) != 3 {
            fmt.Println("Ошибка ввода. Формат: 'fromID toID amount'. Пример: '1 2 125.35'.")
            continue
        }

        fromID, errFrom := strconv.Atoi(inpParts[0])
        toID, errTo := strconv.Atoi(inpParts[1])
        amount, errAmount := strconv.ParseFloat(inpParts[2], 64)

        if errFrom != nil || errTo != nil || errAmount != nil {
            fmt.Println("Ошибка ввода. Пожалуйста, введите ID и размер платежа правильно.")
            continue
        }

        var fromUser *user.User
        var toUser *user.User

        for i, user := range users {
            if user.ID == fromID {
                fromUser = &users[i]
            }

            if user.ID == toID {
                toUser = &users[i]
            }
        }

        if fromUser == nil || toUser == nil {
            fmt.Println("Ошибка ввода. Пользователи с такими ID не найдены.")
            continue
        }

        mu.Lock()
        trsCounter++
        mu.Unlock()

        transactions <- transaction.Transaction{ID: trsCounter, 
                                                From: fromUser, 
                                                To: toUser, 
                                                Amount: amount}
        <- trsResults 
    }

    close(transactions)
    wg.Wait()
    close(trsResults)
}
